import { Component, OnInit } from '@angular/core';
import { GridOptions } from '@ag-grid-community/core';
import { GridConfigService } from '@core/config/grid-config.service';
import { ExportExcelService } from '@core/services/excel/export-excel.service';
import { ApiService } from '@core/services/http/api.service';
import { ApesMessageService } from '@shared/apes/message';
import { ApesContextMenuService } from '@shared/ag-grid-ext/context-menu';
import {AllModules, Module} from "@ag-grid-enterprise/all-modules";

@Component({
  selector: 'oa-monitor',
  templateUrl: './oa-monitor.component.html',
  styleUrls: ['../../purchase-report-form/purchase-report-form.scss'],
})
export class OaMonitorComponent implements OnInit {
  modules: Module[] = AllModules;
  /* 按钮相关 */
  buttonBar = [
    { hide: true, style: 'default', label: '查询', id: 'action_query', loading: false},
    { hide: true, style: 'default', label: '重置', id: 'action_reset' },
    { hide: true, style: 'default', label: '展开查询条件', id: 'action_show' },
    { hide: true, style: 'default', label: '导出', id: 'action_export' },
  ];
  title = '';
  ctx = { model: {} };

  /** Grid 相关 **/
  rowData: any[] = [];
  resultData: any;
  gridOptions: GridOptions;
  pinnedBottomRowData: any[] = [];
  columnDefs: any[] = [];
  rowClassRules: any;
  getContextMenuItems: any;
  height: any = window.innerHeight - 285 + 'px';

  // 报错样式
  hind: string = 'block';
  show: string = 'none';           // 展开查询条件
  days: any;

  store: any[];
  workPost: any[];
  user: any[];
  branch: any[];
  sale = [];

  mdjcTime: any = [];       // 日期
  startValue: Date = null;
  endValue: Date = null;
  id: string = '';                  //单号
  workID: string;                    // 岗位ID
  userID: string;                     // 待办人
  usersID: string;                    // 发起人
  nameID: string;                     // 流程名称
  branchID: any;                     // 待办部门
  branID: any;                      // 发起部门
  checkKeys: string = '0';


  constructor(private apiService: ApiService,
              private gridConfigService: GridConfigService,
              // private router: Router, private event: Events,
              private exportExcelService: ExportExcelService,
              // protected rs: ReuseTabService,
              private contextMenuService:ApesContextMenuService,
              private msg: ApesMessageService) {
    this.columnDefs = [
      { 'headerName': '单号', field: 'businessKey', width: 110 },
      { 'headerName': '流程名称', field: 'name', width: 110 },
      { 'headerName': '版本', field: 'version', width: 120 },
      { 'headerName': '发起人', field: 'processInitiator', width: 150 },
      { 'headerName': '发起部门', field: 'processInitiatingDepartment' },
      { 'headerName': '发起时间', field: 'processInitiatingDate' },
      { 'headerName': '总耗时', field: 'duration', cellRenderer: this.toHour },
      { 'headerName': '当前节点', field: 'curTaskName' },
      { 'headerName': '节点耗时', field: 'nodeDuration', cellRenderer: this.toHour },
      { 'headerName': '待办人', field: 'candidate' },
      { 'headerName': '最近处理记录', field: 'previousInfo' },
    ];

    // 初始化 grid
    this.gridOptions = <GridOptions>{
      toolPanelSuppressSideButtons: true,
      suppressExcelExport: true,
      suppressCsvExport: true,
      suppressSizeToFit: true,
      showToolPanel: false,
      pagination: true,
      paginationPageSize: 100,
      rowHeight: 35,
    };
    this.gridOptions.localeText = gridConfigService.getLocaleText();
    this.getContextMenuItems = (params)=> {
      let result = [
        'copy',
        'separator',
        { name: params.value? params.value :'无数据' },
        'separator',
        {
          name: '查看详情',
          action: () => {
            let data = params.node.data;
            // console.log(data);
            this.send(data);
          },
        },
      ];
      return result;
    };
  }

  //跳转详情页
  send(params: any) {
    // 判断当前单据是否已挂起或者已完成
    if( params.STATE == "挂起" || params.STATE == "完成" ){
      this.msg.warning("该OA已完成或者已挂起，暂不支持处理，请激活流程或者确认流程的完成状态", {"apesDuration": 5000});
      return false;
    }
    let data = {
      'taskId':params.TASKID
    }
    this.contextMenuService.openContextLink(data, 'wf.getTaskByTaskId',{"changeSignFlag":true,"wfFlag": true, "OAInterface":true});
  }

  ngOnInit() {
    this.queryData();
    this.getWorkPost();
    this.getUser();
    this.getBranch();
    this.getStore();
  }

  onEvent(data: any) {

    if (data instanceof MouseEvent) return;
    if (data) {
      if (data.id === 'action_query') {
        this.buttonBar[0].loading = true;
        this.queryData();
      } else if (data.id === 'action_reset') {
        this.action_reset();
      } else if (data.id === 'action_export') {
        this.action_export();
      } else if (data.id === 'action_show') {
        this.action_show();
      }
    }
  }

  // 导出数据
  action_export() {
    if (this.rowData && this.rowData.length === 0) {
      return;
    }
    const columnList = this.gridOptions.columnDefs;
    this.exportExcelService.exportWithDealData(columnList, this.rowData, 'OA流程监控报表');
  }

  // 重置
  action_reset(): void {
    this.mdjcTime = null;
    this.workID = null;
    this.userID = null;
    this.usersID = null;
    this.nameID = null;
    this.branchID = null;
    this.branID = null;
    this.id = null;
    this.checkKeys = '0';
    this.hind = 'block';
  }

  // 展开查询条件
  action_show() {
    if (this.show === 'none') {
      this.show = 'flex';
    } else if (this.show === 'flex') {
      this.show = 'none';
    }
  }

  // 日期相减
  getTimeChang(d1, d2) {
    let day = 24 * 60 * 60 * 1000;
    try {
      let dateArr = d1.split('-');
      let checkDate = new Date();
      checkDate.setFullYear(dateArr[0], dateArr[1] - 1, dateArr[2]);
      let checkTime = checkDate.getTime();

      let dateArr2 = d2.split('-');
      let checkDate2 = new Date();
      checkDate2.setFullYear(dateArr2[0], dateArr2[1] - 1, dateArr2[2]);
      let checkTime2 = checkDate2.getTime();
      this.days = (checkTime - checkTime2) / day;
      if (this.days <= 31) {
        return 'hide';
      } else {
        return 'show';
      }
    } catch (e) {
      return false;
    }
  }

  // 查询按钮事件
  queryData() {
    this.rowData = [];
    this.getDate(this.mdjcTime, 'startValue', 'endValue');
    if (this.endValue !== undefined && this.endValue !== null) {
      this.hind = 'none';
    } else if (this.branID !== undefined && this.branID !== null) {
      this.hind = 'none';
    } else if (this.branchID !== undefined && this.branchID !== null) {
      this.hind = 'none';
    } else if (this.workID !== undefined && this.workID !== null) {
      this.hind = 'none';
    } else if (this.usersID !== undefined && this.usersID !== null) {
      this.hind = 'none';
    } else if (this.userID !== undefined && this.userID !== null) {
      this.hind = 'none';
    } else if (this.nameID !== undefined && this.nameID !== null) {
      this.hind = 'none';
    } else if(this.id !== undefined && this.id !== null &&　this.id != ""){
      this.hind = 'none';
    } else {
      this.hind = 'block';
    }
    //  必须满足以下条件才能调用接口
    if (this.hind === 'none') {
      this.show = 'none';
      this.getTablesData();
    }else{
      this.buttonBar[0].loading = false;
    }
  }

  // 日期转换
  getDate(time: any[], time_ks: string, time_js: string) {
    // debugger;
    if( time == null ){
      this[time_js] = null;
      this[time_ks] = null;
      return;
    }

    let [first, second] = time;
    if (first) {
      this[time_ks] = first.toISOString().slice(0, 10);
    } else {
      this[time_ks] = null;
    }

    if (second) {
      this[time_js] = second.toISOString().slice(0, 10);
    } else {
      this[time_js] = null;
    }

  }

  getTablesData() {
    if(this.id == ''){
      this.id = null;
    }
    let data = {
      'name': this.nameID, 'processToDoUser': this.userID, 'processToDoDepartment': this.branchID,
      'processToDoWorkPost': this.workID, 'finished': this.checkKeys, 'processInitiator': this.usersID,
      'processInitiatingDepartment': this.branID, 'startDate': this.startValue, 'endDate': this.endValue,
      'id':this.id
    };
    this.apiService.post('crm.customComplain.getAllProcess', { 'body': JSON.stringify(data) }).subscribe(
      (body) => {
        if (body) {
          for (let i = 0, len = body.length; i < len; i++) {
            body[i]['duration'] = body[i]['duration'] / 60 / 1000;
            body[i]['nodeDuration'] = body[i]['nodeDuration'] / 60 / 1000;
          }
          this.rowData = body;
          if (this.rowData.length === 0) {
            this.msg.info(`未找到满足条件的数据`);
          }
          this.buttonBar[0].loading = false;
        } else {
          this.msg.info(body.msg);
        }
      });
  }

  // 获取岗位信息
  getWorkPost() {
    let data = { 'size': 1200, page: 0 };
    this.apiService.post('hr.workPost.findAll', { 'body': JSON.stringify(data) }).subscribe(
      (body) => {
        if (body) {
          this.workPost = body.content;
        } else {
          this.msg.info(body.msg);
        }
      });
  }

  // 获取人员信息
  getUser() {
    let data = { 'size': 5000, page: 0 };
    this.apiService.post('aut.user.findAllSimple', { 'body': JSON.stringify(data) }).subscribe(
      (body) => {
        if (body) {
          this.user = body.content;
        } else {
          this.msg.info(body.msg);
        }
      });
  }

  // 获取部门信息
  getBranch() {
    let data = { 'size': 5000, page: 0 };
    this.apiService.post('cm.branch.findAll', { 'body': JSON.stringify(data) }).subscribe(
      (body) => {
        if (body) {
          this.branch = body;
        } else {
          this.msg.info(body.msg);
        }
      });
  }

  // 获取流程信息
  getStore() {
    let data = {};
    this.apiService.post('wf.getProcName', { 'body': JSON.stringify(data) }).subscribe(
      (body) => {
        if (body) {
          let json = {};
          this.store = [];
          body.forEach((item) => {
            let name = item['NAME'];
            if (!json[name]) {
              json[name] = {};
              json[name]['NAME'] = name;
            }
          });
          for (let key in json) {
            this.store.push(json[key]);
          }
        } else {
          this.msg.info(body.msg);
        }
      });
  }

  // 排序 倒序
  sortarr(key) {
    return function (a, b) {
      a[key] == undefined ? a[key] = 0 :
        b[key] == undefined ? b[key] = 0 : 0 ;
      return b[key] - a[key];
    };
  }

  // 时间转换（配合grid调用）
  toHour(params) {
    let key = params.colDef.field;
    let data = params.data[key];
    let a = data >= 0 ? '' : '-';
    data = data >= 0 ? data : -data;

    let day = Math.floor(data / 1440);
    let hour = day >= 0
      ? Math.floor((data - (day * 1440)) / 60)
      : Math.floor(data / 60);
    let minute = hour >= 0
      ? Math.floor(data - (day * 1440) - (hour * 60))
      : data < 0
        ? data
        : Math.floor(data / 60 / 24);

    let time = '';
    if (day > 0) {
      time = a + day + '天' + hour + '小时' + minute + '分钟';
    } else if (hour) {
      time = a + hour + '小时' + minute + '分钟';
    } else if (minute) {
      time = a + minute + '分钟';
    }
    return time;
  }


}
